<template>
  <!-- 卡片视图区域 -->
  <el-card>
    <el-row :gutter="20" justify="end">
<!--      <el-col :span="8">-->
<!--        &lt;!&ndash; 搜索与添加区域 &ndash;&gt;-->
<!--        <el-input placeholder="请输入内容" >-->
<!--          <template #append>-->
<!--            <el-icon><search /></el-icon>-->
<!--          </template>-->
<!--        </el-input>-->
<!--      </el-col>-->
      <el-col :span="4">
        <el-button type="primary" @click="handleAddAcl">添加权限点</el-button>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px;margin-top: 20px"
      height="500px"
      row-key="id"
      border
      stripe
      default-expand-all>
      <el-table-column
        type="index"
        label="权限id"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="权限名称"
      >
      </el-table-column>
      <el-table-column
        label="权限模块"
      >
        <template v-slot="scope">
          {{ getDeptName(scope.row.aclModuleId)  }}
        </template>
      </el-table-column>
      <el-table-column
        prop="type"
        label="类型"
      >
        <template v-slot="scope">
          {{ scope.row.type === 1 ? '菜单' : (scope.row.type === 2 ? '按钮' : '其他')  }}
        </template>
      </el-table-column>
      <el-table-column
        prop="url"
        label="url"
      >
      </el-table-column>
      <el-table-column
        prop="status"
        label="权限状态"
      >
        <template v-slot="scope">
          {{ scope.row.status === 1 ? '有效' : '无效'  }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
      >
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="onEditClick(row)" />
          <el-popover placement="left" :width="400" trigger="click">
            <template #reference>
              <el-button type="primary" size="small" :icon="Checked" @click="onCheckedClick(row)" />
            </template>
            <div>
              <p>所属权限模块</p>
              <el-tag v-for='item in roles' :key="item.id" style="margin-left: 5px">{{ item.name }}</el-tag>
              <p>权限用户列表</p>
              <el-tag v-for='item in users' :key="item.id" style="margin-left: 5px">{{ item.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </el-card>

  <m-dialog v-model="dialogVisible" :title="title" @saveSubmit="submit">
    <el-form :model="form" label-width="120px">
      <el-form-item label="所属权限模块">
        <el-select v-model="currentSelect" @change="aclModuleChange">
          <el-option
            v-for="item in optionSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="form.name" placeholder="请输入权限名称"/>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="currentType" @change="typeChange">
          <el-option
            v-for="item in typeSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="URL">
        <el-input v-if="form.type !== 3" v-model="form.url" placeholder="请输入权限名称"/>
        <el-select v-else v-model="otherState" @change="otherTypeChange">
          <el-option
            v-for="item in otherURL"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="stateValue" @change="stateChange">
          <el-option
            v-for="item in stateSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="顺序">
        <el-input v-model="form.seq" placeholder="请输入顺序名称"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea"/>
      </el-form-item>
    </el-form>
  </m-dialog>

</template>

<script setup>
import { reactive, ref } from 'vue'
import { Edit, Search, Checked } from '@element-plus/icons-vue'
import MDialog from '@/components/MDialog/index.vue'
import { getAclList, addAcl, updateAcl, roleUserAcls } from '@/api/acl'
import { getAclModuleList } from '@/api/acl-module'

const dialogVisible = ref(false)
const tableData = ref([])
const total = ref(0)
const page = ref(1)
const size = ref(10)
const title = ref('权限操作')
const isAdd = ref(true)
const stateValue = ref('有效')
const currentSelect = ref('')
const roles = ref([])
const users = ref([])
const stateSelect = ref([
  {
    label: '有效',
    value: 1
  },
  {
    label: '无效',
    value: 0
  }
])
const currentType = ref(1)
const typeSelect = ref([
  {
    label: '菜单',
    value: 1
  },
  {
    label: '按钮',
    value: 2
  },
  {
    label: '其他',
    value: 3
  }
])
const otherState = ref(1)
const otherURL = ref([
  {
    label: '查看数据',
    value: 1,
    url: 'allData'
  }
])

const otherTypeChange = (value) => {
  otherState.value = value
  form.url = otherURL.value[value].url
}

const stateChange = (value) => {
  form.status = value
}

const aclModuleChange = (value) => {
  form.aclModuleId = value
}

const typeChange = (value) => {
  form.type = value
  if (value === 3) {
    otherState.value = otherURL.value[0].value
    form.url = otherURL.value[0].url
  }
}

const getDeptName = aclModuleId => {
  if (aclModuleId !== 'undefined') {
    if (aclMap[aclModuleId]) {
      return aclMap[aclModuleId].name
    } else {
      return ''
    }
  } else {
    return ''
  }
}

const submit = async () => {
  let result
  if (isAdd.value) {
    result = await addAcl({
      name: form.name,
      aclModuleId: form.aclModuleId,
      type: form.type,
      url: form.url,
      seq: form.seq,
      status: form.status,
      remark: form.remark
    })
  } else {
    result = await updateAcl({
      id: form.id,
      name: form.name,
      aclModuleId: form.aclModuleId,
      type: form.type,
      url: form.url,
      seq: form.sort,
      status: form.status,
      remark: form.remark
    })
  }
  if (result) {
    dialogVisible.value = false
    await getAcl()
  }
}

const handleAddAcl = () => {
  for (const key in form) {
    if (key === 'aclModuleId') {
      form[key] = 0
    } else if (key === 'type' || key === 'status' || key === 'seq') {
      form[key] = 1
    } else {
      form[key] = ''
    }
  }
  isAdd.value = true
  form.aclModuleId = optionSelect.value[0].value
  if (!dialogVisible.value) {
    dialogVisible.value = true
  }
}

const onEditClick = (row) => {
  isAdd.value = false
  form.id = row.id
  form.aclModuleId = row.aclModuleId
  form.name = row.name
  currentType.value = form.type = row.type
  otherState.value = form.url = row.url
  form.sort = row.seq
  form.status = row.status
  form.remark = row.remark
  if (!dialogVisible.value) {
    dialogVisible.value = true
  }
}

const onCheckedClick = async (row) => {
  const result = await roleUserAcls({
    aclId: row.id
  })
  console.log(JSON.stringify(result))
  roles.value = result.roles
  users.value = result.users
}

const allAclModule = ref([])
let optionSelect = ref([])
const aclModuletMap = new Map()
const getAclModule = async () => {
  allAclModule.value = await getAclModuleList()
  console.log('allAclModule.value : ' + JSON.stringify(allAclModule.value))
  recursiveRenderAclModule(allAclModule.value)
  console.log('aclModuletMap' + JSON.stringify(aclModuletMap))
  optionSelect = ref([])
  console.log('recursiveRenderAclModuleSelect' + JSON.stringify(optionSelect.value))
  recursiveRenderAclModuleSelect(allAclModule.value, 1)
  console.log('optionSelect : ' + JSON.stringify(optionSelect.value))
  currentSelect.value = optionSelect.value[0].label
  form.aclModuleId = optionSelect.value[0].value
}
getAclModule()

const getAcl = async () => {
  const result = await getAclList({
    page: page.value,
    size: size.value
  })
  tableData.value = result.list
  total.value = result.total
}
getAcl()

const aclMap = new Map()
const recursiveRenderAclModule = (aclModuleList) => {
  if (aclModuleList && aclModuleList.length > 0) {
    aclModuleList.forEach((aclModule) => {
      console.log('index : ' + aclModule.id)
      console.log('item : ' + JSON.stringify(aclModule))
      aclMap[aclModule.id] = aclModule
      if (aclModule.aclModuleList.length > 0) {
        recursiveRenderAclModule(aclModule.aclModuleList)
      }
    })
  }
}

const recursiveRenderAclModuleSelect = (aclModuleList, level) => {
  level = level | 0
  if (aclModuleList && aclModuleList.length > 0) {
    aclModuleList.forEach((aclModule) => {
      console.log('index : ' + aclModule.id)
      console.log('item : ' + JSON.stringify(aclModule))
      aclMap[aclModule.id] = aclModule
      let blank = ''
      if (level > 1) {
        for (let j = 3; j <= level; j++) {
          blank += '..'
        }
        blank += '∟'
      }
      optionSelect.value.push({
        value: aclModule.id,
        label: blank + aclModule.name
      })
      if (aclModule.aclModuleList.length > 0) {
        recursiveRenderAclModuleSelect(aclModule.aclModuleList, level + 1)
      }
    })
  }
}

const form = reactive({
  id: 0,
  name: '',
  aclModuleId: 0,
  type: 1,
  url: '',
  status: 1,
  seq: '',
  remark: ''
})

/**
 * size 改变触发
 */
const handleSizeChange = currentSize => {
  size.value = currentSize
  getAcl()
}
/**
 * 页码改变触发
 */
const handleCurrentChange = currentPage => {
  page.value = currentPage
  getAcl()
}

</script>

<style lang="scss" scoped>
// @import '~@/style/mixin.scss';
// @import '~@/style/variables.scss';

.app-wrapper {
  // @include clearfix;
  position: relative;
  height: 100%;
  width: 100%;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0,0,0,0.15) !important;
}
</style>
